package com.xr.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xr.blog.dao.BlogConfigMapper;
import com.xr.blog.exception.CustomException;
import com.xr.blog.pojo.BlogConfig;
import com.xr.blog.service.BlogConfigService;
import com.xr.blog.tools.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class BlogConfigServiceImpl extends ServiceImpl<BlogConfigMapper, BlogConfig> implements BlogConfigService {

    @Override
    public Map<String, String> findAllGlobal() {
        Map<String, String> result = new HashMap<>();
        List<BlogConfig> configs = list(new QueryWrapper<BlogConfig>().eq("type",1));
        configs.forEach(variable -> result.put(variable.getName(),variable.getValue()));
        return result;
    }

    @Override
    public String findByName(String name) {
        return getOne(new QueryWrapper<BlogConfig>().select("value").eq("name",name)).getValue();
    }

    @Override
    public void clearCache() {

    }

    @Override
    public <T> T getConfigObject(String name, Class<T> clazz) {
        String value = findByName(name);
        if(StringUtils.isNotBlank(value)){
            return JsonUtils.fromJson(value, clazz);
        }
        try {
            return clazz.newInstance();
        } catch (Exception e) {
            throw new CustomException("获取参数失败");
        }
    }
}